package managedbean.MRP.SaleForecast;

import entity.MRP.SaleForecast.AnnualSaleFigure;
import entity.MRP.SaleForecast.MonthlySaleFigure;
import entity.MRP.SaleForecast.MonthlySaleForecast;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent; 
import javax.faces.event.PhaseEvent;
import session.stateless.MRP.SaleForecast.SaleFigureBeanLocal;
import session.stateless.MRP.SaleForecast.SaleForecastBeanLocal;

@ManagedBean(name="viewSaleForecastManagerBean")
@ViewScoped
public class ViewSaleForecastManagerBean implements Serializable {
    @EJB 
    private SaleForecastBeanLocal saleForecastBeanLocal; 
    @EJB 
    private SaleFigureBeanLocal saleFigureBeanLocal; 
        
    private List<MonthlySaleForecast> monthlySaleForecasts;
    private MonthlySaleForecast monthlySaleForecast;
    private MonthlySaleForecast selectedMonthlySaleForecast;
    private int startMonth, endMonth, startYear, endYear;
    private String startMonthStr, endMonthStr;
    private List<Integer> saleForecastMonths;
    private List<String> saleForecastMonthsStr;
    private String statusMessage;

    public List<MonthlySaleForecast> getMonthlySaleForecasts() {
        return monthlySaleForecasts;
    }

    public void setMonthlySaleForecasts(List<MonthlySaleForecast> monthlySaleForecasts) {
        this.monthlySaleForecasts = monthlySaleForecasts;
    }

    public MonthlySaleForecast getSelectedMonthlySaleForecast() {
        return selectedMonthlySaleForecast;
    }

    public void setSelectedMonthlySaleForecast(MonthlySaleForecast selectedMonthlySaleForecast) {
        this.selectedMonthlySaleForecast = selectedMonthlySaleForecast;
    }

    
    public String getEndMonthStr() {
        return endMonthStr;
    }

    public void setEndMonthStr(String endMonthStr) {
        this.endMonthStr = endMonthStr;
        endMonth = Integer.parseInt(this.endMonthStr.split("/")[0]) - 1;
        endYear = Integer.parseInt(this.endMonthStr.split("/")[1]);
    }

    public String getStartMonthStr() {
        return startMonthStr;
    }

    public void setStartMonthStr(String startMonthStr) {
        this.startMonthStr = startMonthStr;
        startMonth = Integer.parseInt(this.startMonthStr.split("/")[0]) - 1;
        startYear = Integer.parseInt(this.startMonthStr.split("/")[1]);
    }
        
    public List<String> getSaleForecastMonthsStr() {
        boolean changeYear = false;
        Calendar currentDate = Calendar.getInstance();
        int year = currentDate.get(Calendar.YEAR);        
        if (this.getSaleForecastMonths().get(0) != 0){
            changeYear = true;
        }
        else{
            year += 1;
        }
        List<String> month = new ArrayList<String>();

        for(int i:this.getSaleForecastMonths()){
            if (i == 0){
                if (changeYear){
                    year += 1;
                }
                month.add("1/" + year);
            }
            if (i==1){
                month.add("2/" + year);
            }
            if (i==2){
                month.add("3/" + year);
            }
            if (i==3){
                month.add("4/" + year);
            }
            if (i==4){
                month.add("5/" + year);
            }
            if (i==5){
                month.add("6/" + year);
            }
            if (i==6){
                month.add("7/" + year);
            }
            if (i==7){
                month.add("8/" + year);
            }
            if (i==8){
                month.add("9/" + year);
            }
            if (i==9){
                month.add("10/" + year);
            }
            if (i==10){
                month.add("11/" + year);
            }
            if (i==11){
                month.add("12/" + year);
            }
            
        }
        return month;
    }
    
    public List<Integer> getSaleForecastMonths() {
        return saleForecastBeanLocal.getSaleForecastMonths();
    }

    public void initView(PhaseEvent event){
    }  
    
    public void retrieveData(ActionEvent event){ 
        boolean check = false;
        if (this.startYear < this.endYear){
            check = true;
        }
        if (this.startYear == this.endYear){
            if (this.startMonth <= this.endMonth){
                check = true;
            }
        }
        if (!check){
            statusMessage = "Invalid Period. Please Select Again.";
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, statusMessage, ""));
        }
        else{
            List<MonthlySaleForecast> firstMonthlySaleForecasts = null;
            List<MonthlySaleForecast> secondMonthlySaleForecasts = null;
            //generate salefore cast
            if (saleForecastBeanLocal.generateSaleForecasts(this.startMonth, this.startYear, this.endMonth, this.endYear)){
                if (this.startYear == this.endYear){
                    firstMonthlySaleForecasts = saleForecastBeanLocal.getMonthlySaleForecasts(this.startYear, this.startMonth, this.endMonth);
                }
                else {
                    firstMonthlySaleForecasts = saleForecastBeanLocal.getMonthlySaleForecasts(this.startYear, this.startMonth, 11);
                    secondMonthlySaleForecasts = saleForecastBeanLocal.getMonthlySaleForecasts(this.endYear, 0, this.endMonth);
                }

            
                List<MonthlySaleForecast> totalMonthlySaleForecasts = firstMonthlySaleForecasts;
                if (secondMonthlySaleForecasts!=null){
                    for(MonthlySaleForecast m:secondMonthlySaleForecasts){
                        totalMonthlySaleForecasts.add(m);
                    }
                }
                //display data
                this.setMonthlySaleForecasts(totalMonthlySaleForecasts);
            }
            else{
                //display error message;
                statusMessage = "Sale Figure Is Required To Display.";
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, statusMessage, ""));
            }

        }
        
    }   
      
    public int getYear(int month){
        if (this.startYear == this.endYear){
            return startYear;
        }
        else{
            if (month >= this.startMonth) return this.startYear;
            return this.endYear;
        }
    }

    public void updateSaleForecast(ActionEvent event){
        try{
            saleForecastBeanLocal.editSaleForecast(selectedMonthlySaleForecast.getId(), selectedMonthlySaleForecast.getSaleForecastLineItems());
            statusMessage = "Sale Forecast Updated Successfully.";
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,  "Update Sale Figure Result: " + statusMessage, ""));
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    public void validateQuantity(FacesContext context, UIComponent toValidate, Object value){
        
        long qty = -1;
        try{
            qty = (Long) value;
            System.out.println(qty);
        }
        catch(Exception e){
            
        }
        boolean check = true;
        if (qty < 0)
        {
            check = false;
        }
        if (!check) {
            ((UIInput)toValidate).setValid(false);
            FacesMessage message = new FacesMessage("Quantity is invalid. Please re-enter.");
            message.setSeverity(FacesMessage.SEVERITY_WARN);
            context.addMessage(toValidate.getClientId(context), message);
        }
    }      
    
    public Long getPreviousYearQuantity(int month){
        MonthlySaleFigure m = saleFigureBeanLocal.getMonthlySaleFigure(this.getYear(month) - 1, month);
        return m.getTotalProductCaseQuantity();
    }
    
    public Long getPreviousYearPromotionSales(int month){
        MonthlySaleFigure m = saleFigureBeanLocal.getMonthlySaleFigure(this.getYear(month) - 1, month);
        return m.getTotalProductCaseQuantity() - m.getTotalProductCaseQuantityWithoutPromotion();
    }    
    
    public Long getPreviousYearBase(int month){
        MonthlySaleFigure m = saleFigureBeanLocal.getMonthlySaleFigure(this.getYear(month) - 1, month);
        return m.getTotalProductCaseQuantityWithoutPromotion();
    }
    
    public int getYoYGrowth(int month){
        AnnualSaleFigure a = saleFigureBeanLocal.getAnuualSaleFigure(this.getYear(month) - 1);
        return a.getSaleFigureYear();
    }
}
